package gov.kqqzyyy.monkey.orderpad.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.ArrayMap;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.navigation.NavigationView;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import gov.kqqzyyy.monkey.orderpad.R;
import gov.kqqzyyy.monkey.orderpad.broadcastreceiver.GPSInfoReceiver;
import gov.kqqzyyy.monkey.orderpad.broadcastreceiver.WifiStatusReveiver;
import gov.kqqzyyy.monkey.orderpad.mytools.MyBaseActivity;
import gov.kqqzyyy.monkey.orderpad.network.RetrofitUtil;
import gov.kqqzyyy.monkey.orderpad.network.base.BaseObserver;
import gov.kqqzyyy.monkey.orderpad.network.bean.BaseResponse;
import gov.kqqzyyy.monkey.orderpad.object.FloorPatient;
import gov.kqqzyyy.monkey.orderpad.object.FloorsAndBeds;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

@SuppressLint("NonConstantResourceId")
public class NavigationBaseActivity extends MyBaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Spinner mFloorSpinner, mBedSpinner;

    private BaseObserver<List<FloorPatient>> patientsObserver;

    private List<FloorPatient> mFloorPatientList;
    private List<String> mBedsList;

    private String chooseCH;
    ActionBar actionBar;

    public void setmFloorSpinner(Spinner mFloorSpinner) {
        this.mFloorSpinner = mFloorSpinner;
    }

    public void setmBedSpinner(Spinner mBedSpinner) {
        this.mBedSpinner = mBedSpinner;
    }

    public String getChooseCH() {
        return chooseCH;
    }

    private WifiStatusReveiver wifiStatusReveiver;
    private static final int REQUEST_CODE = 0X11;
    private int currentWifi = -1;

    private GPSInfoReceiver gpsInfoReceiver;

    private TextView wifiInfoTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_base);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        actionBar = getSupportActionBar();

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View headerView = navigationView.getHeaderView(0);
        wifiInfoTextView = headerView.findViewById(R.id.header_user_ygxm);

        if (getMyApplication().getLcPatientArrayMap() == null) {
            getMyApplication().setLcPatientArrayMap(new ArrayMap<>());
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        wifiStatusReveiver = new WifiStatusReveiver(this);
        registerReceiver(wifiStatusReveiver, filter);

        IntentFilter gpsFilter = new IntentFilter();
        gpsFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
        gpsInfoReceiver = new GPSInfoReceiver(this);
        registerReceiver(gpsInfoReceiver, gpsFilter);
    }

    public void setWifiInfoTextView(TextView wifiInfoTextView) {
        this.wifiInfoTextView = wifiInfoTextView;
    }

    public void setCurrentWifi(int which) {
        this.currentWifi = which;
    }

    protected void initGPS() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean gpsOn = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gpsOn) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivityForResult(intent, REQUEST_CODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            initGPS();
        }
    }

    protected void connectWIFI(int which) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            int state = wifiManager.getWifiState();
            KLog.d("APE", "wifi state:" + state);
            if (state == WifiManager.WIFI_STATE_ENABLED) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                String ssid = wifiInfo.getSSID().replace("\"", "");
                if (which == 1) {
                    if (ssid.endsWith("jsc")) {
                        KLog.d("APE", "当前已是奇数层WIFI");
                    } else {
                        connectWIFI("KQQZYYY-N-jsc", "kqqzyyy@1_");
                    }
                } else if (which == 2) {
                    if (ssid.endsWith("osc")) {
                        KLog.d("APE", "当前已是偶数层WIFI");
                    } else {
                        connectWIFI("KQQZYYY-N-osc", "kqqzyyy_2@");
                    }
                }
            } else {
                showToast("请先打开WIFI");
            }
        }
    }

    private void connectWIFI(String ssid, String password) {
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (wifiManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            List<WifiConfiguration> configurationList = wifiManager.getConfiguredNetworks();
            boolean found = false;
            for (WifiConfiguration config : configurationList
            ) {
                if (config.SSID.replace("\"", "").equals(ssid)) {
                    found = true;
                    wifiManager.enableNetwork(config.networkId, true);
                    showProgressDialog("切换WIFI中");
                    break;
                }
            }
            if (!found) {
                WifiConfiguration configuration = new WifiConfiguration();
                configuration.allowedAuthAlgorithms.clear();
                configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                configuration.allowedGroupCiphers.clear();
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                configuration.allowedKeyManagement.clear();
                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                configuration.allowedPairwiseCiphers.clear();
                configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                configuration.allowedProtocols.clear();
                configuration.SSID = "\"" + ssid + "\"";
                configuration.preSharedKey = "\"" + password + "\"";
                configuration.hiddenSSID = true;
                configuration.status = WifiConfiguration.Status.ENABLED;
                int networkid = wifiManager.addNetwork(configuration);
                boolean enable = wifiManager.enableNetwork(networkid, true);
                showProgressDialog("切换WIFI中");
//                KLog.d("APE", enable);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (patientsObserver != null) {
            patientsObserver.doCancelRequest();
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(wifiStatusReveiver);
        unregisterReceiver(gpsInfoReceiver);
        super.onDestroy();
        System.gc();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        // Handle navigation view item clicks here.
        Intent intent;
        switch (item.getItemId()) {
//            case R.id.nav_setting:
//            case R.id.nav_change:
//            case R.id.nav_xbrry:
//                Toast.makeText(getApplicationContext(), "功能未开启", Toast.LENGTH_SHORT).show();
//                break;
            case R.id.nav_wifi_change:
                int whichWifi = currentWifi == 2 || currentWifi == 0 ? 1 : 2;
                connectWIFI(whichWifi);
                break;
            case R.id.nav_logout:
                if (!(this instanceof UserLoginActivity)) {
                    intent = new Intent(this, UserLoginActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                }
                break;
            case R.id.nav_exit:
                new AlertDialog.Builder(this)
                        .setTitle("退出提醒")
                        .setMessage("确定要退出该应用？")
                        .setNegativeButton("确定", (dialog, which) -> {
                            Intent startMain = new Intent(Intent.ACTION_MAIN);
                            startMain.addCategory(Intent.CATEGORY_HOME);
                            startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(startMain);
                            System.exit(0);
                        })
                        .setPositiveButton("取消", (dialog, which) -> dialog.dismiss()).create().show();
                break;
            case R.id.nav_jrhc:
                if (!(this instanceof PatientJRHCActivity)) {
                    intent = new Intent(this, PatientJRHCActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                }
                break;
        }
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //病区楼层变更，加载楼层房间
    public void changeFloor() {
        String chooseFloor = getMyApplication().getChooseFloor();
        setActionBarTitle("当前病区：" + chooseFloor + "       登陆用户：" + getMyApplication().getXtgl().getYhxm());
        mFloorPatientList = getMyApplication().getLcPatientArrayMap().get(chooseFloor);
        if (mFloorPatientList != null && mFloorPatientList.size() > 0) {
            doSetBeds(chooseFloor);
        } else {
            doGetFloorPatients(chooseFloor);
        }
    }

    public void setActionBarTitle(String title) {
        if (actionBar != null) {
            actionBar.setTitle(title);
        }
    }

    public void doSetBeds(String floor) {
        if (mBedSpinner != null) {
            mBedsList = getMyApplication().getLcchArrayMap().get(floor);
            Collections.sort(Objects.requireNonNull(mBedsList), String::compareTo);
            String[] items = mBedsList.toArray(new String[0]);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_spinner_bed, items);
            mBedSpinner.setAdapter(adapter);
            int pos = mBedsList.indexOf(getMyApplication().getChooseCH());
            if (pos > 0) {
                mBedSpinner.setSelection(pos);
            } else {
                clearChoosePatientInfo();
            }
        }
    }

    public void setFloor() {
        List<String> mFloorList = getMyApplication().getmFloorsNameList();
        String[] items = mFloorList.toArray(new String[0]);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_spinner_bed, items);
        mFloorSpinner.setAdapter(adapter);
        String chooseFloor = getMyApplication().getChooseFloor();
        if (!chooseFloor.equals("")) {
            mFloorSpinner.setSelection(mFloorList.indexOf(chooseFloor));
        }
    }

    private void doGetFloorPatients(String floor) {
//        KLog.d("APE","获取病人数据");
        showProgressDialog("获取病人数据中");
        getMyApplication().setGettingPatientInfo(true);
        List<String> list = getMyApplication().getLcbrArrayMap().get(floor);
        StringBuilder param = new StringBuilder();
        for (String brch : Objects.requireNonNull(list)
        ) {
            if (param.toString().equals("")) {
                param.append(brch);
            } else {
                param.append(",").append(brch);
            }
        }

        Observable<BaseResponse<List<FloorPatient>>> observable = RetrofitUtil.getInstence().getFloorPatients(param.toString());
        patientsObserver = new BaseObserver<List<FloorPatient>>() {
            @Override
            protected void onSuccees(BaseResponse<List<FloorPatient>> t) {
                cancelProgressDialog();
                mFloorPatientList = t.getData();
                if (mFloorPatientList != null && mFloorPatientList.size() > 0) {
                    Collections.sort(mFloorPatientList, (arg0, arg1) -> arg0.getBrbh().compareTo(arg1.getBrbh()));
                } else {
                    mFloorPatientList = new ArrayList<>();
                }
                getMyApplication().getLcPatientArrayMap().put(floor, mFloorPatientList);
                doSetBeds(floor);
            }

            @Override
            protected void onFailure(Throwable e, boolean isNetWorkError) {
                cancelProgressDialog();
                showToast("获取病人信息失败\n" + e.getMessage());
                getMyApplication().setGettingPatientInfo(false);
                doCancelLoad();
            }

            @Override
            protected void onCodeError(BaseResponse<List<FloorPatient>> t) {
                super.onCodeError(t);
                cancelProgressDialog();
                showToast("获取病人信息失败\n" + t.getSubmsg());
                getMyApplication().setGettingPatientInfo(false);
                doCancelLoad();
            }

        };
        observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(patientsObserver);
//        int buildNum = getMySharedPreferences().getInt("BUILD_NUM", 1);
//        getFloorPatientsCall = MyServiceUtil.getFloorPatientsCall(buildNum, param.toString());
//        Callback<String> callback = new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                String result = response.body();
//                if (result != null) {
//                    Gson gson = new Gson();
//                    mFloorPatientList = gson.fromJson(result, new TypeToken<List<FloorPatient>>() {
//                    }.getType());
//                    if (mFloorPatientList != null && mFloorPatientList.size() > 0) {
//                        KLog.d("APE", "获取楼层病人数据成功！");
//                        Collections.sort(mFloorPatientList, (arg0, arg1) -> arg0.getBrbh().compareTo(arg1.getBrbh()));
//                    } else {
//                        mFloorPatientList = new ArrayList<>();
//                    }
//                    getMyApplication().getLcPatientArrayMap().put(floor, mFloorPatientList);
//                    doSetBeds(floor);
//                }
//                getMyApplication().setGettingPatientInfo(false);
//                doCancelLoad();
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                Toast.makeText(getApplicationContext(), "获取病人数据失败，请稍后重试！", Toast.LENGTH_SHORT).show();
//                getMyApplication().setGettingPatientInfo(false);
//                doCancelLoad();
//            }
//        };
//        getFloorPatientsCall.enqueue(callback);
    }

    public FloorPatient doGetSelectPatientInfo(int position) {
        chooseCH = mBedsList.get(position);
        getMyApplication().setChooseCH(chooseCH);
        String brbh = "";
        for (FloorsAndBeds object : getMyApplication().getmFloorList()
        ) {
            if (object.getCh().equals(chooseCH)) {
                brbh = object.getBrbh();
                break;
            }
        }
        if (!brbh.equals("")) {
            for (FloorPatient patient : mFloorPatientList
            ) {
                if (patient.getBrbh().equals(brbh)) {
                    return patient;
                }
            }
        } else {
            Toast.makeText(getApplicationContext(), "该床病人不存在！", Toast.LENGTH_LONG).show();
        }
        return null;
    }

    public void doCancelLoad() {
        if (!getMyApplication().isGettingCPXX() && !getMyApplication().isGettingPatientInfo()) {
            cancelProgressDialog();
        }
    }

    public void setWIFIInfo(String info) {
        if (info == null) {
            KLog.d("APE", "wifi info is null");
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                String ssid = wifiInfo.getSSID().replace("\"", "");
                if (!ssid.contains("<unknown ssid>")) {
                    setWIFIInfo(ssid);
                }
            }
        } else {
            if (wifiInfoTextView != null) {
                new Handler().postDelayed(() -> {
                    String text = getString(R.string.login_text_4) + info;
                    wifiInfoTextView.setText(text);
                    cancelProgressDialog();
                }, 1000);
            } else {
                new Handler().postDelayed(() -> setWIFIInfo(info), 1000);
            }
        }
    }

    @SuppressLint("UnspecifiedImmutableFlag")
    protected void showNotification(String titile, String message) {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //点击通知本身会显示ResultActivity
        Intent resultIntent = new Intent(this, NavigationBaseActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
         PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        Notification notification;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel("APE_CHANNEL", "APE_NOTICE", NotificationManager.IMPORTANCE_HIGH);
            mNotificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(NavigationBaseActivity.this)
                    .setChannelId("APE_CHANNEL")
                    .setContentTitle(titile)
                    .setContentIntent(resultPendingIntent)
                    .setContentText(message)
                    .setSmallIcon(R.mipmap.ic_launcher).build();
        } else {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //构造Builder对象
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(titile)
                    .setContentText(message)
                    .setDefaults(Notification.DEFAULT_ALL);//全部
            notification = builder.build();
            builder.setContentIntent(resultPendingIntent);
        }
        mNotificationManager.notify(1, notification);
    }

}
